<?php
namespace hema\device\engine;


/**
 * 易联云打印机驱动模块
 * 测试机型号：K4-WH
 */
class Yilianyun extends Basics
{
    /**
     * 构造方法
     */
    public function __construct($dev_type, $device, $data, $tpl)
    {
        parent::__construct($dev_type, $device, $data, $tpl);
    }
    
    /**
    * 打印订单接口
    */
    public function print()
    {
        if($this->tpl==0){
            $content = $this->make_order_templet($this->data,$this->device['values']['prt_num']);//制作订单模板
        }else{
            $content = $this->make_refund_templet($this->data,$this->device['values']['prt_num']);//制作退单模板
        }
        $params = $this->params();
        $params['machine_code'] = $this->device['dev_id'];//打印机终端号
        $params['origin_id'] = $this->data['order_id'];//订单编号
        $params['content'] = $content;//打印内容
        $result = json_decode($this->http_post_json($params,'print/index'),true);
        return true;
    }
    
    /**
    * 授权绑定打印机
    */
    public function add()
    {
        $data = $this->data;
        $params = $this->params();
        $params['print_name'] = $data['dev_name'];//自定义打印机名称(可填)
        $params['machine_code'] = $data['dev_id'];//打印机终端号
        $params['msign'] = $data['dev_key'];//打印机终端密钥
        $result = json_decode($this->http_post_json($params,'printer/addprinter'),true);
        return $result;
    }
    
    /**
    * 删除授权绑定的打印机
    */
    public function delete(){
        $params = $this->params();
        $params['machine_code'] = $this->data['dev_id'];//打印机编号
        $result = json_decode($this->http_post_json($params,'printer/deleteprinter'),true);
        return $result;
    }
    
    /**
    * 获取打印机状态接口 
    */
    public function status(){
        $params = $this->params();
        $params['machine_code'] = $this->data['dev_id'];//打印机编号
        $res = json_decode($this->http_post_json($params,'printer/getprintstatus'),true);
        if($res['error']==0){
            $msg = '离线';
            if($res['body']['state']==1){
                $msg = '正常';
            }
            if($res['body']['state']==2){
                $msg = '缺纸';
            }
            return $msg;
        }
        return '未知';
    }

    /**
    * 获取Token
    */
    public function getToken()
    {
        $time = time();
        $params = [
            'client_id' => $this->config['app_key'],
            'timestamp' => $time,
            'sign' => $this->getSign($time),
            'id' => $this->uuid4(),
            'scope' => 'all'
        ];
        $params['grant_type'] = 'client_credentials';
        $result = json_decode($this->http_post_json($params,'oauth/oauth'),true);
        if($result['error']==0){
            return $result['body']['access_token'];
        }
        return ''; //返回空值
    }

    public function edit()
    {
        
    }
    public function push()
    {
        
    }
    
    /**
    * 公共参数
    */
    private function params(){
        $time = time();         //请求时间
        return $params = [
            'client_id' => $this->config['app_key'],
            'access_token' => $this->config['access_token'],
            'timestamp' => $time,
            'sign' => $this->getSign($time),
            'id' => $this->uuid4(),
        ];
    }
    
    /**
    * 生成签名
    */
    private function getSign($timestamp)
    {
        return md5($this->config['app_key'] . $timestamp . $this->config['app_secret']);
    }

    /**
    * 生成uuid4
    */
    private function uuid4(){
        mt_srand((double)microtime() * 10000);
        $charid = strtolower(md5(uniqid(rand(), true)));
        $hyphen = '-';
        $uuidV4 =
            substr($charid, 0, 8) . $hyphen .
            substr($charid, 8, 4) . $hyphen .
            substr($charid, 12, 4) . $hyphen .
            substr($charid, 16, 4) . $hyphen .
            substr($charid, 20, 12);
        return $uuidV4;
    }
    
    
    //发送post请求
    /**
     * PHP发送Json对象数据
     * @return string
     */
    private function http_post_json($data,$url)
    {
        $url = $this->config['api_url'] . $url;
        $data = http_build_query($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); // 解决数据包大不能提交
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }

    /**
     * 制作订单模板
     * $data 订单数据
     * $n 打印份数
     * 58mm的机器,一行打印16个汉字,32个字母;
     */
    private function make_order_templet($data,$n)
    {
        if($data['order_mode']['value']==10){
            if(isset($data['table']['table_name'])){
                $title = $data['table']['table_name'];
            }else{
                $title = '堂食'.$data['row_no'].'号';
            }
        }
        if($data['order_mode']['value']==20){
            $title = '外卖'.$data['row_no'].'号';
        }
        if($data['order_mode']['value']==30){
            $title = '自取'.$data['row_no'].'号';
        }
        $content = '<MN>'.$n.'</MN>';
        $content .= '<FS><center># '.$title.' #</center></FS>';
        if($data['arrive_time']['value']>0){
            $content .= '到店时间:'.$data['arrive_time']['text']."\n";
        }
        $content .= str_repeat('-', 32);
        $content .= '<center>'.$data['shop']['shop_name'].'</center>';
        if($data['pay_status']['value'] != 30){
            if($data['transaction_id']){
                $content .= '<center>-- 微信支付 --</center>';
            }else{
                $content .= '<center>-- 余额支付 --</center>';
            }
            $content .= '支付时间:'.datetime($data['pay_time'])."\n";
        }else{
            $content .= '<center>-- 后付款 --</center>';
        }
        $content .= "<FS>名称        数量</FS>\n";//16=4+8+4
        $content .= str_repeat('-', 32);
        //循环拼接打印模板
        for ($i = 0; $i < sizeof($data['goods']); $i++) {
                $goods_name = $data['goods'][$i]['goods_name'].$data['goods'][$i]['goods_attr'];//产品名字
                $total_num = $data['goods'][$i]['total_num'];   //产品数量
                //设置名称字符长度
                $lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
                for($n=$lan;$n<13;$n++){
                    $goods_name .= ' ';
                }
                $content .= '<FS>' . $goods_name . '×' . $total_num."</FS>\n";
        }
        $content .= str_repeat('-', 32);
        $content .= '商品金额：+￥'.$data['total_price']."\n";
        if($data['express_price']>0){
            $content .= '配送费用：+￥'.$data['express_price']."\n";
        }
        if($data['pack_price']>0){
            $content .= '餐盒费用：+￥'.$data['pack_price']."\n";
        }
        if($data['ware_price']>0){
            $content .= '餐具调料：+￥'.$data['ware_price']."\n";
        }
        if($data['activity_price']>0){
            $content .= '优惠金额：-￥'.$data['activity_price']."\n";
        }
        $content .= '实付金额：￥'.$data['pay_price']."\n";
        if($data['flavor']){
            $content .= '口味要求：'.$data['flavor']."\n";
        }
        if($data['message']){
            $content .= '顾客留言：'.$data['message']."\n";
        }
        if($data['order_mode']['value']==20){
            $content .= '配送地址：'.$data['address']['detail']."\n";
            $content .= '接 收 人：'.$data['address']['name'].$data['address']['phone']."\n";
        }
        $content .= '<FS><center># '.$title.' # 完</center></FS>';
        $content .= "\n";
        return $content;
    }
    
    /**
     * 制作退单模板
     * $data 退单数据
     * $n 打印份数
     * 58mm的机器,一行打印16个汉字,32个字母;
     */
    private function make_refund_templet($data,$n)
    {
        if($data['order_mode']['value']==10){
            if(isset($data['table']['table_name'])){
                $title = $data['table']['table_name'];
            }else{
                $title = '堂食'.$data['row_no'].'号';
            }
        }
        if($data['order_mode']['value']==20){
            $title = '外卖'.$data['row_no'].'号';
        }
        if($data['order_mode']['value']==30){
            $title = '自取'.$data['row_no'].'号';
        }
        $content = '<MN>'.$n.'</MN>';
        $content .= '<FS><center># 退单 #</center></FS>';
        $content .= '<FS><center>- '.$title.' -</center></FS>';
        $content .= str_repeat('-', 32);
        $content .= '<center>'.$data['shop']['shop_name'].'</center>';
        $content .= "<FS>名称        数量</FS>\n";//16=4+8+4
        $content .= str_repeat('-', 32);
        //循环拼接打印模板
        for($i = 0; $i < sizeof($data['goods']); $i++) {
            if($data['goods'][$i]['refund_num']>0){
                $goods_name = $data['goods'][$i]['goods_name'].$data['goods'][$i]['goods_attr'];//产品名字
                $refund_num = $data['goods'][$i]['refund_num']; //产品数量
                //设置名称字符长度
                $lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
                for($n=$lan;$n<13;$n++){
                    $goods_name .= ' ';
                }
                $content .= '<FS>' . $goods_name . '×' . $refund_num."</FS>\n";
            }
        }
        $content .= str_repeat('-', 32);
        $content .= '支付金额：￥'.$data['pay_price']."\n";
        $content .= '退款金额：￥'.$data['refund_price']."\n";
        $content .= '退款理由：'.$data['refund_desc']."\n";
        $content .= "<FS><center># 退款 # 完</center></FS>\n\n";
        return $content;
    }

}
